//
//  SectionViewController.m
//  NewsReader
//
//  Created by blacksun on 10-10-27.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "SectionViewController.h"
#import "RootViewController.h"
#import "ItemListController.h"


@implementation SectionViewController
@synthesize titleLabel,summaryLabel,imageView,activity,section,deleteButton,lastFeedTitleLabel,customButton;
@synthesize imageDownloadsInProgress;
@synthesize closeImageView;
@synthesize shadowView;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
	self.titleLabel.text = self.section.sectionName;
	self.summaryLabel.text = self.section.summary;
	//给图片加圆角
	self.imageView.layer.cornerRadius = 6;
	self.imageView.layer.masksToBounds = YES;
	//给UIView加阴影
	self.shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
	self.shadowView.layer.shadowOpacity = 0.7f;
	self.shadowView.layer.shadowOffset = CGSizeMake(0.0f, 5.0f);
	self.shadowView.layer.shadowRadius = 5.0f;
	self.shadowView.layer.masksToBounds = NO;
	UIBezierPath *path = [UIBezierPath bezierPathWithRect:self.shadowView.bounds];
	self.shadowView.layer.shadowPath = path.CGPath;
	
	[self updateImage];
}
-(IBAction) deleteSection:(id)sender{	[self.view  removeFromSuperview];
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	RootViewController *parentController = (RootViewController *)delegate.navigationController.visibleViewController; 
	[parentController.needDeleteSections addObject:self.section];
	NSInteger index = [parentController.sectionViewControllers indexOfObject:self];
	[parentController.sectionViewControllers removeObject:self];
	
	parentController.pagecontrol.numberOfPages = [ModelParseUtil reloadScrollView:parentController.scrollView withControllers:parentController.sectionViewControllers
																	needAnimation:YES startIndex:index];
	
}
- (IBAction) sectionClicked:(id)sender{
	//NSLog(@"clicked...");
	ItemListController *childController = [[ItemListController alloc] init];
	childController.section = self.section;
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	childController.user = delegate.user;
	[delegate.navigationController pushViewController:childController animated:YES]; 
	[childController release];
}




- (void)updateImage{
    
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    
	NSString *imageUrl = self.section.imageUrl;
	//NSLog(@"last=%@",section.lastFeedImageUrl);
	//NSLog(@"old=%@",section.oldImageUrl);
	if ((NSNull *)self.section.lastFeedImageUrl != [NSNull null]) {
		imageUrl = self.section.lastFeedImageUrl;
	}
	if ([@"" isEqualToString:imageUrl]) {
		self.imageView.image = [UIImage imageNamed:@"detail_loading.png"];
		[self.activity stopAnimating];
		return;
	}
	
	if ([ImageStorgeUtil isImageExistInSystem:imageUrl]) {
		UIImage *image = [[UIImage alloc] initWithContentsOfFile:[ImageStorgeUtil getFullPathWithImagePath:imageUrl]];
		self.imageView.image = image;
		[image release];
		self.lastFeedTitleLabel.text = self.section.lastFeedTitle;
		[self.activity stopAnimating];
	}else{
		if ([ImageStorgeUtil isImageExistInSystem:self.section.oldImageUrl]) {
			UIImage *image = [UIImage imageWithContentsOfFile:[ImageStorgeUtil getFullPathWithImagePath:self.section.oldImageUrl]];
			self.imageView.image = image;
		}else {
			self.imageView.image = [UIImage imageNamed:@"detail_loading.png"];
		}
		
		self.lastFeedTitleLabel.text = self.section.oldFeedTitle;
        if (delegate.networkState){
            [self.activity startAnimating];
            ImageDownloader * iconDownloader = [[ImageDownloader alloc] init];
            
            iconDownloader.identifier = imageUrl;
            iconDownloader.delegate = self; 
            iconDownloader.imageUrl = imageUrl;
            [imageDownloadsInProgress setObject:iconDownloader forKey:imageUrl];
            [iconDownloader startDownload];
            [iconDownloader release];
		}
	}
}

// called by our ImageDownloader when an icon is ready to be displayed
- (void)imageLoaded:(UIImage *)image forIdentify:(NSObject *)identifier{
	self.lastFeedTitleLabel.text = self.section.lastFeedTitle;
    ImageDownloader *iconDownloader = [imageDownloadsInProgress objectForKey:identifier];
    if (iconDownloader != nil)
    {
		if (image!=nil) {
            //NSLog(@"%@",self.section.lastFeedImageUrl);
			[ImageStorgeUtil saveImageData:UIImagePNGRepresentation(image) toFilePath:self.section.lastFeedImageUrl];
			self.section.lastFeedImageUrl = [ImageStorgeUtil getFilePathWithImagePath:self.section.lastFeedImageUrl];
			[UIView beginAnimations:@"animationID" context:nil];
			[UIView setAnimationDuration:0.5f];
			[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			[UIView setAnimationRepeatAutoreverses:NO];
			[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];//oglFlip, fromLeft 
			UIImageView *newimageView = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10.0, 145.0, 110.0)];
			newimageView.image = image;
			//给图片加圆角
			newimageView.layer.cornerRadius = 6;
			newimageView.layer.masksToBounds = YES;
			[self.view insertSubview:newimageView atIndex:1];
			[self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:2];
			[UIView commitAnimations];
			[self.imageView removeFromSuperview];
			self.imageView = newimageView;
			[newimageView release];
		}
		[self.activity stopAnimating];
		[self.imageDownloadsInProgress removeObjectForKey:identifier];
    }
}


- (void)needToDeleteMySelf{
	self.customButton.enabled = NO;
	self.deleteButton.hidden = NO;
	self.closeImageView.hidden = NO;
	CGRect oldFrame = self.deleteButton.frame;
	self.deleteButton.frame = CGRectMake(-5.0,-5.0,oldFrame.size.width,oldFrame.size.height);
	[self.view.layer addAnimation:[self shakeAnimation] forKey:@"rorate"];
}
- (void)resumeNormal{
	self.customButton.enabled =YES;
	self.deleteButton.hidden = YES;
	self.closeImageView.hidden = YES;
	[self.view.layer removeAnimationForKey:@"rorate"];
}
- (CAAnimation *)shakeAnimation{
	CAKeyframeAnimation * animation; animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation.z"]; 
	[animation setDuration:0.5];
	[animation setRepeatCount:10000];
	// Try to get the animation to begin to start with a small offset 
	// that makes it shake out of sync with other layers. 
	srand([[NSDate date] timeIntervalSince1970]); 
	float rand = (float)random();
	[animation setBeginTime: CACurrentMediaTime() + rand * 0.0000000001];
	
	
	NSMutableArray *values = [NSMutableArray array]; // Turn right
	[values addObject:[NSNumber numberWithFloat: -1 * M_PI / 180]]; // Turn left
	[values addObject:[NSNumber numberWithFloat: 1 * M_PI / 180]];// Turn right
	[values addObject:[NSNumber numberWithFloat: -1 * M_PI / 180]]; // Set the values for the animation
	[animation setValues:values]; 
	return animation;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}
- (void)dealloc {
	NSArray *downloaders = [self.imageDownloadsInProgress allValues];
	[downloaders makeObjectsPerformSelector:@selector(cancelDownload)];
	[self.imageDownloadsInProgress release];
	[self.lastFeedTitleLabel release];
	[self.titleLabel release];
	[self.summaryLabel release];
	[self.imageView release];
	[self.activity release];
	[self.customButton release];
	[self.section release];
	[self.closeImageView release];
	[self.shadowView release];
    [super dealloc];
}

@end
